﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Http;
using Woodbase.CodeBase.UI;
using System.Xml.Linq;
using Woodbase.CodeBase.WVR.Objects;
using System.Web.Script.Serialization;
using System.Configuration;

namespace WoodbaseVideoRental.Pages.Movies
{
    public partial class Create : WoodbaseBasePage
    {
        List<Actor> actors = new List<Actor>();
        protected void Page_Load(object sender, EventArgs e)
        {
            for (var i = 1950; i < DateTime.Now.Year + 5; i++)
            {
                ddlYear.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
            }
            ddlYear.Items.FindByValue(DateTime.Now.Year.ToString()).Selected = true;
            ddlYear.DataBind();

            using (HttpClient client = new HttpClient(ConfigurationManager.AppSettings["webservicebasepath"]))
            {
                using (HttpResponseMessage msg = client.Get("Genres"))
                {
                    lbxGenres.Items.Clear();
                    msg.EnsureStatusIsSuccessful();
                    var content = msg.Content.ReadAsXElement();
                    lbxGenres.Items.AddRange(content.DescendantsAndSelf("Genre").Select(x => new ListItem() { Text = x.Attribute("name").Value.Substring(0, 1).ToUpper() + x.Attribute("name").Value.Substring(1) }).ToArray());
                }
                lbxGenres.DataBind();
                
                using (HttpResponseMessage msg = client.Get("Actors"))
                {
                    msg.EnsureStatusIsSuccessful();
                    var xmlActorList = msg.Content.ReadAsXElement().DescendantsAndSelf("Actor");
                    actors.AddRange(xmlActorList.Select(x => new Actor()
                    {
                        GivenName = x.Attribute("given-name").Value,
                        LastName = x.Attribute("last-name").Value,
                        BirthYear = int.Parse(x.Attribute("birth-year").Value),
                        Sex = (x.Attribute("gender").Value == "MALE") ? Gender.MALE : Gender.FEMALE,
                        Nationality = x.Attribute("nationality").Value
                    }));
                    lbxActors.DataSource = actors;
                    lbxActors.DataTextField = "FullName";
                    lbxActors.DataBind();
                }
            }
        }

        protected void btnCreateMovie_Click(object sender, EventArgs ea)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var selGenres = js.Deserialize<string[]>(selectedGenres.Text);
            var newActors = js.Deserialize<List<Actor>>(newActorsList.Text);
            var actorCollection = new List<Actor>();
            actorCollection.AddRange(newActors);

            using (HttpClient client = new HttpClient(ConfigurationManager.AppSettings["webservicebasepath"]))
            {
                foreach (ListItem si in lbxActors.Items)
                {
                    if (si.Selected)
                    {
                        using (HttpResponseMessage msg = client.Get("Actor/" + HttpUtility.UrlEncode(si.Text)))
                        {
                            msg.EnsureStatusIsSuccessful();
                            XElement actor = msg.Content.ReadAsXElement();
                            actorCollection.Add(new Actor() { GivenName = actor.Attribute("given-name").Value, LastName = actor.Attribute("last-name").Value, BirthYear = int.Parse(actor.Attribute("birth-year").Value), Nationality = actor.Attribute("nationality").Value, Sex = (actor.Attribute("gender").Value == "MALE") ? Gender.MALE : Gender.FEMALE });
                        }
                    }
                }

                foreach (var a in newActors)
                {
                    var t = HttpContentExtensions.CreateXmlSerializable<Actor>(a, typeof(Actor));
                    client.Put("Actor", t);
                }

                Movie m = new Movie() { MTitle = txbTitle.Text, PlayTime = int.Parse(txbRuntime.Text), Genres = selGenres.Select(x => new Genre() { Name = x }).ToList<Genre>(), Actors = actorCollection, ProductionYear = int.Parse(ddlYear.SelectedValue) };
                using(HttpResponseMessage msg = client.Put("Movie", HttpContentExtensions.CreateXmlSerializable<Movie>(m, typeof(Movie)))){
                    msg.EnsureStatusIsSuccessful();
                }
            }
            Response.Redirect("/");
        }
    }
}